package org.oos.atom.elements;

import java.io.Serializable;

import com.google.api.client.util.Key;

/**
 * 
 * Represents the geografical location given by the Geography Markup Language
 * 
 * @author pablo.gonzalez@11870.com
 * 
 */
public class GeoLocation implements Serializable, Cloneable {

	private static final long serialVersionUID = 1L;

	@Key("gml:Point")
	private Point point;

	private Float[] coords;

	private Float radius = 50f;

	private static final GeoLocation flyweight = new GeoLocation();

	public static GeoLocation create(Float latitude, Float longitude) {
		GeoLocation result = null;
		try {
			result = flyweight.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			return null;
		}
		result.coords = new Float[] { latitude, longitude };
		return result;
	}

	@Override
	public GeoLocation clone() throws CloneNotSupportedException {
		return (GeoLocation) super.clone();
	}

	public static class Point implements Serializable, Cloneable {

		private static final long serialVersionUID = 1L;
		@Key("gml:pos")
		public String position;

		@Override
		public Point clone() throws CloneNotSupportedException {
			return (Point) super.clone();
		}
	}

	public boolean hasCoords() {
		if (coords == null && point != null) {
			String[] stringCoords = point.position.split(" ");
			coords = new Float[] { Float.valueOf(stringCoords[0]),
					Float.valueOf(stringCoords[1]) };
		}
		return coords != null;
	}

	public Float getLatitude() {
		if (hasCoords()) {
			return coords[0];
		}
		return null;
	}

	public Float getLongitude() {
		if (hasCoords()) {
			return coords[1];
		}
		return null;
	}

	public void setRadius(Float radius) {
		this.radius = radius;
	}

	public Float getRadius() {
		return radius;
	}

	public static GeoLocation create(Double latitude, Double longitude) {
		return create(latitude.floatValue(), longitude.floatValue());
	}

}
